﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using CashResource;
using System.Windows.Forms;
using Cash.DialogFroms;
using System.Collections.ObjectModel;
using CashCommon;
using Cash.Model;
using System.Globalization;
using Comparers;

namespace Cash
{
    public partial class FormDocuments : Form
    {
        public FormDocuments()
        {
            InitializeComponent();
            this.Text = CommonText.DocFormTitle;

            AssignEventForButtonMenu();
        }

        //Назначение событий для кнопок меню
        private void AssignEventForButtonMenu()
        {
            this.tsbPeriodCash.Click += new EventHandler(tsbPeriodCash_Click);
            this.tsbNewCash.Click += new EventHandler(tsbNewCash_Click);
            this.tsbEditCash.Click += new EventHandler(tsbEditCash_Click);
        }

        #region Events

        private void FormDocuments_Load(object sender, EventArgs e)
        {
            OpenOnDate(this._dtFrom, this._dtTo);
        }
        private void dataGridCashes_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dataGridCashes.Columns[e.ColumnIndex].Name.Equals("N_Amount"))
            {
                e.Value = ((decimal)e.Value).ToString("C");
            }
            if (dataGridCashes.Columns[e.ColumnIndex].Name.Equals("D_Date"))
            {
                e.Value = ((DateTime)e.Value).ToShortDateString();
            }
            //if (e.ColumnIndex == 1 && e.RowIndex == 1)
            //{
            //    DataGridViewCell cell = this.dataGridCashes.Rows[e.RowIndex].Cells[e.ColumnIndex];
            //    cell.ToolTipText = "cccvssdfasdfcvs";
            //}
        }
        private void dataGridCashes_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            #region N_State - отрисовка
            if (this.dataGridCashes.Columns["N_State"].Index == e.ColumnIndex && e.RowIndex >= 0)
            {
                Rectangle rectCell = new Rectangle(e.CellBounds.X, e.CellBounds.Y, e.CellBounds.Width, e.CellBounds.Height);
                Rectangle rectPrint = new Rectangle(e.CellBounds.X + 10, e.CellBounds.Y, 20, 20);
                Rectangle rectPost = new Rectangle(e.CellBounds.X + 40, e.CellBounds.Y, 20, 20);

                using (Brush gridBrush = new SolidBrush(this.dataGridCashes.GridColor),
                        backColorBrush = new SolidBrush(e.CellStyle.BackColor),
                        backSelectedBrush = new SolidBrush(e.CellStyle.SelectionBackColor)
                        )
                {
                    using (Pen gridLinePen = new Pen(gridBrush))
                    {
                        // Erase the cell.
                        if (dataGridCashes.Rows[e.RowIndex].Selected)
                            e.Graphics.FillRectangle(backSelectedBrush, e.CellBounds);
                        else
                            e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
                            e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
                            e.CellBounds.Bottom - 1);
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
                            e.CellBounds.Top, e.CellBounds.Right - 1,
                            e.CellBounds.Bottom);

                        if (e.Value != null)
                        {
                            switch (Convert.ToInt32(e.Value))
                            {
                                case 1:
                                    e.Graphics.DrawImage(Properties.Resources.Print, rectPrint);
                                    break;
                                case 2:
                                    e.Graphics.DrawImage(Properties.Resources.Write, rectPrint);
                                    e.Graphics.DrawImage(Properties.Resources.Print, rectPost);
                                    break;
                            }
                        }
                        e.Handled = true;
                    }

                }
            }
            #endregion

            #region Отрисовка иконки сохранения в сетке

            if (e.ColumnIndex == -1 && e.RowIndex == -1)
            {
                Rectangle rectCell = new Rectangle(e.CellBounds.X, e.CellBounds.Y, e.CellBounds.Width, e.CellBounds.Height);
                Rectangle rectPrint = new Rectangle(e.CellBounds.X + 1, e.CellBounds.Y + 4, 14, 14);

                using (Brush gridBrush = new SolidBrush(this.dataGridCashes.GridColor),
                        backColorBrush = new SolidBrush(e.CellStyle.BackColor),
                        backSelectedBrush = new SolidBrush(e.CellStyle.SelectionBackColor)
                        )
                {
                    using (Pen gridLinePen = new Pen(gridBrush))
                    {
                        e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
                            e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
                            e.CellBounds.Bottom - 1);
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
                            e.CellBounds.Top, e.CellBounds.Right - 1,
                            e.CellBounds.Bottom);

                        e.Graphics.DrawImage(Properties.Resources.Save, rectPrint);
                    }
                    e.Handled = true;
                }
            }

            #endregion
        }
        private void tsbEditCash_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                if (dataGridCashes.Rows.Count == 0)
                    return;

                Form frmNewCash = new FormNewCash(Convert.ToInt32(dataGridCashes.SelectedRows[0].Cells["LINK"].Value, CultureInfo.InvariantCulture));
                Tools.OpenMdiForm(frmNewCash, Tools.MainForm);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        private void dataGridCashes_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            tsbEditCash_Click(null, null);
        }
        private void tsbPeriodCash_Click(object sender, EventArgs e)
        {
            FormParamsOfJournal frmPeriodOfJournal = new FormParamsOfJournal(this._dtFrom, this._dtTo);
            frmPeriodOfJournal.OnResultOk += new DelegateDataFromDataTo(OpenOnDate);
            frmPeriodOfJournal.ShowDialog();
        }
        private void tsbNewCash_Click(object sender, EventArgs e)
        {
            FormNewCash frmNewCash = new FormNewCash(0);
            Form[] forms = Tools.DocumentsForm();
            foreach (Form form in forms)
            {
                FormDocuments formDocument = form as FormDocuments;
                if(formDocument != null)
                    frmNewCash.OnCheckPrinted += new DlegateWithoutParams(formDocument.OpenDefault);
            }
            Tools.OpenDialogMdiForm(frmNewCash, Tools.MainForm);
        }
        private void tsbDeleteCash_Click(object sender, EventArgs e)
        {
            if (dataGridCashes.Rows.Count == 0)
                return;

            if (Tools.ShowMessage(CommonText.ConfirmDelete) == DialogResult.OK)
            {
                int currentCell = 0;
                int selectedRows = 0;

                currentCell = dataGridCashes.CurrentCell == null ? 0 : dataGridCashes.CurrentCell.RowIndex;
                selectedRows = dataGridCashes.SelectedRows.Count;

                int result = CashRegister.RemoveById((from DataGridViewRow dataGridRow in dataGridCashes.SelectedRows
                                                      select Convert.ToInt32(dataGridRow.Cells["LINK"].Value, CultureInfo.InvariantCulture)).ToArray<int>());

                if (result == 0)
                {
                    OpenOnDate(this._dtFrom, this._dtTo);
                    if ((selectedRows == 1) && (currentCell > 0))
                        dataGridCashes.CurrentCell = this.dataGridCashes.Rows[--currentCell].Cells[dataGridCashes.FirstDisplayedCell.ColumnIndex];
                }

            }
        }
        private void tsbRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                OpenOnDate(this._dtFrom, this._dtTo);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

        }
        private void dataGridCashes_MouseUp(object sender, MouseEventArgs e)
        {
            SetEnableToolBar();
        }
        private void dataGridCashes_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control)
            {
                switch (e.KeyCode)
                {
                    case Keys.N:
                        tsbNewCash_Click(null, null);
                        return;
                    case Keys.O:
                        tsbEditCash_Click(null, null);
                        return;
                    case Keys.R:
                        tsbRefresh_Click(null, null);
                        return;
                    case Keys.A:
                        tsbRefresh_Click(null, null);
                        return;
                    case Keys.D:
                        tsbPeriodCash_Click(null, null);
                        return;
                    default:
                        return;
                }
            }
            if (e.KeyCode == Keys.Delete)
                tsbDeleteCash_Click(null, null);
        }
        private void dataGridCashes_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            SetEnableToolBar();
            if (e.ColumnIndex == -1 && e.RowIndex == -1)
            {
                
                _backgroundWorker = new BackgroundWorker();
                _backgroundWorker.DoWork += new DoWorkEventHandler(bgwApplySettings);
                RunWorkerCompletedEventHandler rwc = new RunWorkerCompletedEventHandler(bgwCompletedApplySettings);
                _backgroundWorker.RunWorkerCompleted += rwc;
                _backgroundWorker.RunWorkerAsync();

                Adjustment.Default.RegisterGrid.Clear();
                Adjustment.Default.RegisterGrid.AddRange((
                    from DataGridViewColumn c in dataGridCashes.Columns
                    select new GridColumn(c.Name, c.HeaderText, c.DisplayIndex, c.Width)).ToArray());
                if (dataGridCashes.SortedColumn != null)
                {
                    Adjustment.Default.RegisterGrid.SortedColumn = dataGridCashes.SortedColumn.Name;
                    Adjustment.Default.RegisterGrid.SortedAsc = dataGridCashes.SortOrder == SortOrder.Ascending ? true : false;
                }
                Adjustment.Save();
                Adjustment.Load();
                System.Threading.Thread.Sleep(2000);
                bgwCompletedApplySettings(null, null);
            }
        }
        private void tcDocuments_SelectedIndexChanged(object sender, EventArgs e)
        {
            TabControl tb = sender as TabControl;
            if (tb != null)
            {
                DataView dv = new DataView(_seq.DT);
                dv.RowFilter = String.Format("{0}='{1}'", "EMPLOYERNAME", tb.SelectedTab.Text);
                dataGridCashes.DataSource = dv;
                dataGridCashes.Parent = tb.SelectedTab;

                // Обновление данных в статус баре
                tsslDocCheckCount.Text = String.Format(CommonText.DocumentsFormCheckCountTitle, dv.Count);
                double sum = (
                    from DataRowView item in dv 
                    select Convert.ToDouble(item["N_AMOUNT"])
                    ).Sum();
                tsslDocCheckSum.Text = string.Format(CommonText.DocumentsFormCheckSumTitle, sum.ToString("C"));
            }
            ApplySaveSettingToGrid();
        }

        #endregion

        #region Helper

        private void SetEnableToolBar()
        {
            bool isSelectedRow = this.dataGridCashes.SelectedRows.Count > 0;

            // Видимость кнопок
            tsbEditCash.Enabled = isSelectedRow;
            tsbDeleteCash.Enabled = isSelectedRow;

        }
        private void OpenOnDate(DateTime dtFrom, DateTime dtTo)
        {
            this._dtFrom = dtFrom;
            this._dtTo = dtTo;

            SqlSwitch sqlSwitch = new SqlSwitch();
            sqlSwitch.Add("D_Date_Search", String.Format("{0},{1}", _dtFrom.ToString("yyyyMMdd"), _dtTo.ToString("yyyyMMdd")), SqlCondition.btw, SqlType.sqlDate, Direction.input);
            sqlSwitch.Add("F_Division", CashEmployer.Inst.F_Division, SqlCondition.in_enum, SqlType.sqlInt, Direction.input);
            this._seq = CashRegister.OpenSequence(ref dataGridCashes, sqlSwitch, new List<string>() { "N_STATE", "D_DATE", "C_NAME", "N_CODE", "N_AMOUNT", "C_CORRACCOUNT", "ABONENTNAME", "ABONENTCODE", "EMPLOYERNAME" });
            SplitByUsers();

            tcDocuments_SelectedIndexChanged(tcDocuments, null);
            SetEnableToolBar();
        }
        private void SplitByUsers()
        {
            // Данные по пользователям
            tcDocuments.TabPages["tabPageCurrentUser"].Text = CashEmployer.Inst.C_FIO;
            TabPage[] tb = (
                from DataRow row in _seq.DT.Rows
                group row by row["EMPLOYERNAME"].ToString() into res
                select new TabPage(res.Key)
                ).ToArray();
            if (tb.Count() > 0)
                tcDocuments.TabPages.AddRange(tb.Except(from TabPage tb1 in tcDocuments.TabPages select tb1, new TabPageComparer()).ToArray());
            else
            {
                dataGridCashes.Parent = tcDocuments.TabPages[0];
                for (int i = tcDocuments.TabPages.Count-1; i > 0; i--)
                {
                    tcDocuments.TabPages.RemoveAt(i);
                }
            }
        }
        private void OnCheckPrinted()
        {
            OpenOnDate(this._dtFrom, this._dtTo);
        }
        public void OpenDefault()
        {
            OpenOnDate(this._dtFrom, this._dtTo);
        }
        private void ApplySaveSettingToGrid()
        {
            // Загрузка сохраненных настроек столбцов таблицы
            foreach (DataGridViewColumn item in dataGridCashes.Columns)
            {
                GridColumn[] gridColumn = (
                    from GridColumn gridColumnItem in Adjustment.Default.RegisterGrid.Items
                    where gridColumnItem.Name == item.Name
                    select gridColumnItem
                    ).ToArray();
                if (gridColumn.Count() > 0)
                {
                    item.DisplayIndex = gridColumn[0].Position;
                    item.Width = gridColumn[0].Width;
                }
            }
            string sortColumn = Adjustment.Default.RegisterGrid.SortedColumn;
            if (Tools.AsNullString(sortColumn) != "")
                dataGridCashes.Sort(dataGridCashes.Columns[sortColumn], 
                    Adjustment.Default.RegisterGrid.SortedAsc ? ListSortDirection.Ascending : ListSortDirection.Descending);
        }
        private void bgwApplySettings(object sender, DoWorkEventArgs e)
        {
            _frmProgress = new FrmProgress(CommonText.ProgressFormTitleSaveProperties);
            _frmProgress.ShowDialog();
        }
        private void bgwCompletedApplySettings(object sender, RunWorkerCompletedEventArgs e)
        {
            if (_frmProgress != null)
                _frmProgress.DialogResult = DialogResult.OK;
        }

        #endregion

        #region Fields

        private DateTime _dtFrom = DateTime.Today;
        private DateTime _dtTo = DateTime.Today;
        private Sequence _seq;
        private BackgroundWorker _backgroundWorker;
        private FrmProgress _frmProgress;

        #endregion

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            Tools.GetHelp("operation_doc_list", HelpNavigator.Topic);
        }

        private void FormDocuments_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F1)
                toolStripButton2_Click(null, null);
        }

    }
}
